import 'dart:typed_data';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:get/get.dart' hide MultipartFile hide FormData;
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:package_info/package_info.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/helper.dart';
import 'package:yp/pages/mall_app/feedback_history/view.dart';
import 'package:yp/pages/mall_app/opinion_feedback/hud.dart';
import 'package:yp/services/api.dart';

import '../../../router.dart';
import 'state.dart';

class OpinionFeedbackLogic extends GetxController {
  final state = OpinionFeedbackState();

  @override
  void onInit() {
    super.onInit();

    state.feedbackCategoryIndex = -1;
    state.controller = TextEditingController();
    state.userFocusNode = FocusNode();
    var _mobile = SpUtil.getString('number');
    if (_mobile.length > 4) {
      var sufixLength = (_mobile.length - 4) ~/ 2;
      var prefixLength = _mobile.length - 4 - sufixLength;
      state.mobile = _mobile.substring(0, prefixLength) +
          '****' +
          _mobile.substring(_mobile.length - sufixLength, _mobile.length);
    } else {
      state.mobile = _mobile;
    }

    getLabels();
  }

  void getLabels() {
    var paramsIntegral = {
      'access_token': SpUtil.getString('token'),
      'head_ec_shop_num_id': SpUtil.getInt('storeShopNum'),
      'group_query_sign': 1, //分组信息查询标识,1：查询分组信息 2：不查询
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'page_num': 1,
      'page_size': 100
    };
    Api.queryFeedbackLabels(paramsIntegral).listen((event) {
      if (event['code'] == 0) {
        state.labels = event['group_infos'];
      }
      update();
    });
  }

  Future pickImage() async {
    if (state.assets.length >= 9) {
      return;
    }
    List<Asset> resultList = [];
    resultList = await MultiImagePicker.pickImages(
      maxImages: 9 - state.assets.length,
      enableCamera: true,
      cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
      materialOptions: MaterialOptions(
        actionBarColor: "#FCCD00",
        actionBarTitle: "选择图片",
        allViewTitle: "所有图片",
        useDetailsView: false,
        selectCircleStrokeColor: "#000000",
      ),
    );
    if (resultList == null || resultList.isEmpty) {
      return;
    }
    // EasyLoading.show();
    for (var asset in resultList) {
      state.assets.add(asset);
      ByteData byteData = await asset.getByteData();
      Uint8List originData = byteData.buffer.asUint8List();

      var imageData = await FlutterImageCompress.compressWithList(
        originData,
        minHeight: 960,
        minWidth: 540,
        quality: 80,
      );
      state.images.add(imageData);
    }
    EasyLoading.dismiss();
    update();
  }

  void deletePhoto(index) {
    print(index);
    if (state.assets.length <= index - 1) {
      return;
    }
    state.assets.removeAt(index);
    state.images.removeAt(index);
    update();
  }

  Future uploadImages() async {
    if (state.images.length == 0) {
      submit();
      return;
    }
    state.urls = [];
    for (var i = 0; i < state.images.length; i++) {
      var imageData = state.images[i];
      var asset = state.assets[i];
      MultipartFile multipartFile = MultipartFile.fromBytes(
        imageData,
        filename: asset.name,
      );
      Api.upImage(
        FormData.fromMap({
          "file": multipartFile,
        }),
      ).listen((event) {
        if (event["code"] == 0) {
          state.urls.add(event["result"][0]["url"]);
          if (i == state.assets.length - 1) {
            //提交评论
            submit();
          } else {
            dismissHud();
          }
        } else {
          dismissHud();
        }
      });
    }
  }

  submitAction() {
    if (state.feedbackCategoryIndex < 0 ||
        state.feedbackCategoryIndex > state.labels.length - 1) {
      showToast('请选择您要反馈的问题类型');
      return;
    }

    var commentContent = state.controller.text;
    if (commentContent == null || commentContent.isEmpty) {
      showToast('请输入您的反馈意见');
      return;
    }
    showHud();
    uploadImages();
  }

  Future<void> submit() async {
    var info = state.labels[state.feedbackCategoryIndex];
    var commentContent = state.controller.text;
    String version = '';
    var phone_version = '';
    var deviceInfo = DeviceInfoPlugin();
    if (GetPlatform.isAndroid) {
      AndroidDeviceInfo info = await deviceInfo.androidInfo;
      phone_version = info.version.codename;
    } else if (GetPlatform.isIOS) {
      var info = await deviceInfo.iosInfo;
      phone_version = info.systemVersion;
    }

    if (!kIsWeb) {
      PackageInfo packageInfo = await PackageInfo.fromPlatform();

      version = packageInfo.version ?? "";
    }
    var paramsIntegral = {
      // 'ec_shop_num_id': SpUtil.getInt('storeShopNum'),
      "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
      'platform_id': 2, //固定传2
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'group_num_id': info['group_num_id'],
      'feedback_content': commentContent,
      'feedback_image_urls': state.urls.join(','),
      'system_version': version,
      'phone_version': phone_version
    };
    print(paramsIntegral);
    Api.submitFeedback(paramsIntegral).listen((event) {
      if (event['code'] == 0) {
        Get.to(FeedbackHistoryPage(),arguments: RefreshController()); // 意见反馈详情
      }
      // dismissHud();
    }); 
  }

  void feedbackCategoryChoose(int index) {
    state.feedbackCategoryIndex = index;
    update();
  }
}
